<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="title">图书管理系统</div>
      <el-form 
        ref="loginFormRef"
        :model="loginForm" 
        :rules="loginRules" 
        label-position="top">
        
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名"
            prefix-icon="User" 
            size="large" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            prefix-icon="Lock" 
            size="large"
            show-password 
            @keyup.enter="handleLogin" />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="login-button" 
            size="large"
            @click="handleLogin">
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <div v-if="debugMode" class="debug-info">
        <p>调试信息:</p>
        <pre>{{ debugInfo }}</pre>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'

// 表单引用
const loginFormRef = ref(null)
// 路由实例
const router = useRouter()
// 用户存储
const userStore = useUserStore()
// 加载状态
const loading = ref(false)
// 调试模式
const debugMode = ref(true)
// 调试信息
const debugInfo = ref('')

// 登录表单数据
const loginForm = reactive({
  username: 'admin',  // 默认值便于测试
  password: '123456'  // 默认值便于测试
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 挂载时只检查调试信息，不要清除token
onMounted(() => {
  // 收集调试信息
  debugInfo.value = `
路由信息: ${JSON.stringify(router.currentRoute.value.fullPath)}
Token状态: ${localStorage.getItem('token') || '无'}
  `
})

// 登录方法
const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        console.log('开始登录请求，提交数据:', JSON.stringify(loginForm))
        
        // 清除之前可能存在的无效token
        userStore.resetState()
        
        const result = await userStore.loginAction(loginForm)
        console.log('登录成功，结果:', JSON.stringify(result))
        
        // 确认token已正确存储
        const storedToken = localStorage.getItem('token')
        console.log('存储的token:', storedToken)
        
        // 更新调试信息
        debugInfo.value = `
登录响应: ${JSON.stringify(result)}
存储Token: ${storedToken || '无'}
        `
        
        ElMessage.success('登录成功')
        
        // 如果token已正确存储，立即导航到首页，不需要延迟
        if (storedToken) {
          // 等待一个很短的时间，确保token已完全保存
          setTimeout(() => {
            const redirectPath = router.currentRoute.value.query.redirect || '/'
            console.log('有token，立即重定向到:', redirectPath)
            router.replace(redirectPath)
          }, 200)
        } else {
          console.error('登录成功但未能获取token')
          ElMessage.warning('登录成功但未能获取token，请尝试重新登录')
        }
      } catch (error) {
        console.error('登录错误:', error)
        ElMessage.error(error.message || '登录失败')
        
        // 更新调试信息
        debugInfo.value = `
登录错误: ${error.message || '未知错误'}
        `
      } finally {
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确填写登录信息')
      return false
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #EBF4FF 0%, #E6F0FE 100%);
  position: relative;
  overflow: hidden;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 400px;
  height: 400px;
  background: linear-gradient(135deg, rgba(51, 102, 255, 0.1) 0%, rgba(51, 102, 255, 0.05) 100%);
  border-radius: 50%;
  transform: translate(150px, -200px);
  z-index: 0;
}

.login-container::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 300px;
  height: 300px;
  background: linear-gradient(135deg, rgba(51, 102, 255, 0.1) 0%, rgba(51, 102, 255, 0.05) 100%);
  border-radius: 50%;
  transform: translate(-100px, 100px);
  z-index: 0;
}

.login-card {
  width: 450px;
  padding: 30px;
  border-radius: var(--radius-large);
  box-shadow: var(--shadow-large);
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 1;
  border: none;
  animation: fadeIn 0.5s ease-out;
}

.title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 30px;
  color: var(--text-primary);
  position: relative;
  padding-bottom: 15px;
}

.title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(90deg, var(--primary-color), #4d7aff);
  border-radius: 3px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--text-primary);
}

:deep(.el-input__wrapper) {
  box-shadow: none !important;
  border: 1px solid var(--border-color);
  border-radius: var(--radius-medium);
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover) {
  border-color: var(--primary-color);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(51, 102, 255, 0.2) !important;
}

:deep(.el-input__inner) {
  height: 45px;
}

.login-button {
  width: 100%;
  height: 45px;
  border-radius: var(--radius-medium);
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
  background: linear-gradient(45deg, var(--primary-color), #4d7aff);
  border: none;
  box-shadow: 0 4px 10px rgba(51, 102, 255, 0.25);
  transition: all 0.3s;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(51, 102, 255, 0.35);
}

.debug-info {
  margin-top: 30px;
  padding: 15px;
  background-color: rgba(0, 0, 0, 0.03);
  border-radius: var(--radius-medium);
  font-size: 12px;
  overflow: auto;
  max-height: 200px;
  color: var(--text-secondary);
  border: 1px dashed var(--border-color);
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 500px) {
  .login-card {
    width: 90%;
    padding: 20px;
  }
}
</style> 